/**
 * @author 涂建刚 2014-08-22
 */
// 百度地图API功能

//-----------全局变量定义区 开始------------------------------------------
var map;
// Map实例
var localS;
//本地搜索实例
var ambulanceArray = [];
//车辆数组 BMap.Marker
var ambGpsTrackArray = [];
//车辆轨迹数组 BMap.Marker
var alarmEventArray = [];
//呼救事件数组
var stationArray = [];
//分站数组
var hospitalArray = [];
//医院数组
var spotOverlay;
//标注图标
var spotCircle;
//标注圆圈
var routeBegin;
//导航起点
var routeEnd;
//导航终点
var addressOverlay;
//地址图标
var telOverlay;
//电话图标
var isInAccept = false;
//是否在受理中
var isSpoted = false;
//是否标注过
var myDis;
//测距工具
var ambDriving;
//车辆路径规划
//var isAmbListOpen = false;		//车辆列表是否打开
var panCursor;
//地图鼠标默认样式
var isMapAddClickEvent = false;
//地图是否绑定了单击事件
var checkedAmbulanceId = "";
//勾选跟踪的车辆编码
var ambGpsTrackLine;
//轨迹回放连线
var lushu;
//路书功能
//2016-7-26 zch add volunteer
var volunteerArray = [];
//志愿者数组BMap.Marker
//var volunGridArray = [];
//全局变量 ，用于存放每次添加的志愿者 ，用于grid 的分页使用,也用于存储志愿者个人信息

//add2020-09-21 plq
var fbAmbArray = [];      //防病车辆 add2020-10-10 plq

//-----------全局变量定义区 结束------------------------------------------

//获取Document
function Gid(id) {
	return document.getElementById(id);
}

//加载地图
function mapInit() {
	map = new BMap.Map("map");
	// 创建Map实例
	map.addControl(new BMap.NavigationControl());
	// 添加平移缩放控件
	map.addControl(new BMap.ScaleControl());
	// 添加比例尺控件
	map.addControl(new BMap.OverviewMapControl());
	//添加缩略地图控件
	map.enableScrollWheelZoom();
	//启用滚轮放大缩小
    //map.addControl(new BMap.MapTypeControl());
    //添加地图类型控件
    //添加地图类型控件 edit 2020-09-22 plq 自定义可选的地图类型(去掉默认的三维类型)
	map.addControl(new BMap.MapTypeControl({
	    mapTypes: [
            BMAP_NORMAL_MAP,
            BMAP_SATELLITE_MAP,
            BMAP_HYBRID_MAP
	    ],
	    anchor: BMAP_ANCHOR_BOTTOM_RIGHT //表示控件停靠的位置--右下
	}));

    //map.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
    //map.setMapStyle({style:'grassgreen'});//add2020-09-22 plq 百度地图个性化模板

	//添加路况信息
	var ctrl = new BMapLib.TrafficControl({
		showPanel : false //是否显示路况提示面板
	});
	map.addControl(ctrl);
	//ctrl.setAnchor(BMAP_ANCHOR_BOTTOM_RIGHT);
	ctrl.setAnchor(BMAP_ANCHOR_BOTTOM_LEFT);
	var size = ctrl.defaultOffset;
	size.height = 40;
	size.width = 10;
	ctrl.setOffset(size);
	//路况信息结束

	//var myCity = new BMap.LocalCity();
	//myCity.get(myFun);
	map.centerAndZoom(new BMap.Point(initX, initY), initZoom);

	acceptStart(false);
	Gid('addressquery').style.display = "none";
	//$('#addressquery2').hide();
	Gid('routeResult').style.display = "none";

	panCursor = map.getDefaultCursor();
	//保存默认鼠标样式

	//添加右键菜单
	var menu = new BMap.ContextMenu();

	var txtMenuItem = [{
		text : '以此为起点',
		callback : function(pt) {
			if (routeBegin) {
				routeBegin.setPosition(pt);
			} else {
			    //var myIcon = new BMap.Icon("../../images/icon_st.png", new BMap.Size(30, 55));
			    var myIcon = new BMap.Icon(iconUrlHead + "images/icon_st.png", new BMap.Size(30, 55));
				routeBegin = new BMap.Marker(pt, {
					icon : myIcon
				});
				map.addOverlay(routeBegin);
			}
			//selfRoute(0);
			var tab = $('#selfRouteTab').tabs('getSelected');
			var index = $('#selfRouteTab').tabs('getTabIndex', tab);
			selfRoute(index);
		}
	}, {
		text : '以此为终点',
		callback : function(pt) {
			if (routeEnd) {
				routeEnd.setPosition(pt);
			} else {
			    //var myIcon = new BMap.Icon("../../images/icon_en.png", new BMap.Size(30, 55));
			    var myIcon = new BMap.Icon(iconUrlHead + "images/icon_en.png", new BMap.Size(30, 55));
				routeEnd = new BMap.Marker(pt, {
					icon : myIcon
				});
				map.addOverlay(routeEnd);
			}

			var tab = $('#selfRouteTab').tabs('getSelected');
			var index = $('#selfRouteTab').tabs('getTabIndex', tab);
			selfRoute(index);
		}
	}];
	for (var i = 0; i < txtMenuItem.length; i++) {
		menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
	}
	map.addContextMenu(menu);

	$("#ambTree").tree({
		onClick : function(node) {
			var isLeaf = $("#ambTree").tree("isLeaf", node.target);
			if (isLeaf) {
				//alert(node.text);  // 在用户点击的时候提示
				panToAmb(node.id);
			}
		},
		onBeforeCheck : function(node, checked) {
			if (checked) {//准备选中，先清空其他选中项
				if (checkedAmbulanceId != "") {
					var node = $('#ambTree').tree('find', checkedAmbulanceId);
					$('#ambTree').tree('uncheck', node.target);
				}
			} else {
				checkedAmbulanceId = "";
			}
		},

		onCheck : function(node, checked) {
			if (checked) {//选中 跟踪
				checkedAmbulanceId = node.id;
			}
		}
	});

	$('#tbQueryResult').datagrid({
		singleSelect : true,
		pagination : true, //分页控件
		rownumbers : false, //行号
		pagesize : 10,
		data : [],
		pageList : [10, 20],
		onClickRow : function(index, row) {
			//alert(row.title+ ' ' + row.lng);
			clickQueryResult(row.title, row.address, row.lng, row.lat);
		},
		onDblClickRow : function(index, row) {
			//alert(row.title+ ' ' + row.lng);
			dblClickQueryResult(row.title, row.address, row.lng, row.lat);
		},
		columns : [[{
			field : 'title',
			title : '名称',
			width : 150
		}, {
			field : 'address',
			title : '地址',
			width : 300
		}, {
			field : 'lng',
			hidden : true
		}, {
			field : 'lat',
			hidden : true
		}]]
	});

	$('#querycontent2').searchbox({
		searcher : function(value, name) {
			localSearchOnlyData();
		},
		prompt : '请输入值'
	});

	$('#addressquery2').window({
		title : "地名搜索",
		width : 450,
		closed : true,
		top : 10,
		left : $(window).width() - 700,
		collapsible : false,
		minimizable : false,
		maximizable : false,
		onClose : function() {
			clearSearch2();
		}
	});

	//2016-7-26 zch add  volunteer  start
	if (!EnableVolunteer) {//隐藏按钮
		Gid('btnVolunteerTd').style.display = "none";
	}
	$('#volunteerWindow').window({
		title : "志愿者人员列表",
		width : 320,
		closed : true,
		top : 60,
		left : $(window).width() - 525,
		collapsible : false,
		minimizable : false,
		maximizable : false,
		onClose : function() {
			//UnAbleAllStandbyVolun();
			//去除地图上所有待命志愿者
		}
	});

	$('#volunteerGrid').datagrid({
		singleSelect : true,
		pagination : true, //分页控件
		rownumbers : false, //行号
		pagesize : 10,
		fitColumns : true,
		data : volunteerArray,
		pageList : [10, 20],
		onClickRow : function(index, row) {
			panToVolun(row.userid);
		},
		columns : [[{
			field : 'name',
			title : '姓名',
			width : 110
		}, {
			field : 'volunteerType',
			title : '志愿者类型',
			width : 130
		}, {
			field : 'telphone',
			title : '电话',
			width : 150
		}, {
			field : 'userid',
			hidden : true

		}]]
	});
	
	

	$('#selfRouteTab').tabs({
		onSelect : function(title, index) {
			selfRoute(index);
		},
		tools : [{
			iconCls : 'icon-cancel',
			handler : function() {
				//alert('添加')
				clearAmbRoute();
				map.removeOverlay(routeBegin);
				routeBegin = null;
				map.removeOverlay(routeEnd);
				routeEnd = null;
				$('#selfRouteTab').hide();
			}
		}]

	});
	$('#selfRouteTab').hide();
	//alert(navigator.userAgent);
	//window.external.webMapLoadComplete();
	//通知窗体

	// 分站数组  stationArray    医院数组 hospitalArray
	//2016-8-17 zch 增加  当缩放等级小于
	map.addEventListener('zoomend', function () {
	    var zoomlevel = map.getZoom();
	    if (zoomlevel < hideZoomLevel) {//缩放级别小于隐藏级别   就隐藏
	        for (var i = 0; i < stationArray.length; i++) {
	            stationArray[i].hide();
	        }
	        for (var j = 0; j < hospitalArray.length; j++) {
	            hospitalArray[j].hide();
	        }
	    } else {//缩放级别大于隐藏级别   就显示
	        for (var i = 0; i < stationArray.length; i++) {
	            stationArray[i].show();
	        }
	        for (var j = 0; j < hospitalArray.length; j++) {
	            hospitalArray[j].show();
	        }
	    }

	    //add2020-09-22 plq 当缩放等级小于 隐藏所有标注点的文本标注 start
	    console.log(zoomlevel);
	    var allOverlay = map.getOverlays();//获取所有覆盖物
	    for (var i = 0; i < allOverlay.length; i++) {
	        //注意：在使用allOverlay[i]要进行是否是Marker的判断，因为getOverlays()后会得到类型不同的对象
	        if (allOverlay[i] instanceof BMap.Marker) {
	            //console.log(allOverlay[i]);
	            if (zoomlevel < hideZoomLevel) { //缩放级别小于隐藏级别   就隐藏
	                if (allOverlay[i].getLabel() instanceof BMap.Label) {
	                    allOverlay[i].getLabel().setStyle({ display: 'none' }); //隐藏文本标注
	                }
	            }
	            else {
	                //判断获取的是否是Label对象，否则没有setStyle()方法
	                if (allOverlay[i].getLabel() instanceof BMap.Label) {
	                    allOverlay[i].getLabel().setStyle({ display: 'block' }); //显示文本标注
	                }
	            }
	        }
	    };
	    //end

	});


}
// end

//获取当前城市
function myFun(result) {
	var cityName = result.name;
	map.centerAndZoom(cityName, 12);
	// 初始化地图,设置中心点坐标和地图级别。
}

//进入受理
function acceptStart(isStart) {
	isInAccept = isStart;
	if (isStart == true) {
		//document.getElementById("btnSpot").style.display="";
		//document.getElementById("tel").style.display="block";
		//document.getElementById("tdSpot").style.width="56px";
		//document.getElementById("tdtel").style.width="40px";
		//document.getElementById("freeTd").style.width="160px";
		//Gid("btnSpot").src = "images/control/spot_1.png";
		//Gid("btnTel").src = "images/control/tel_1.png";

	} else//退出受理
	{
		//document.getElementById("btnSpot").style.display="none";
		//document.getElementById("tel").style.display="none";
		//document.getElementById("tdSpot").style.width="0px";
		//document.getElementById("tdtel").style.width="0px";
		//document.getElementById("freeTd").style.width="240px";
		//Gid("btnSpot").src = "images/control/spot_3.png";
		//Gid("btnTel").src = "images/control/tel_3.png";
		map.removeOverlay(spotOverlay);
		//清除定位图标
		map.removeOverlay(spotCircle);
		//清除定位圆圈
		map.removeOverlay(telOverlay);
		//清除电话图标
		isSpoted = false;
		//退出受理后 清除 是否标注标志
		clearAmbRoute();
		//清除路线规划
		clearSuggestion();

		//2016-8-8 zch 受理结束，将待命的志愿者图标清除
		//UnAbleAllStandbyVolun();
	}
}

//标注定位报警地点,参数：坐标点
function markSpotOverlay(pt) {
	map.removeOverlay(spotOverlay);
	//先清除上次定位图标
	map.removeOverlay(spotCircle);
	map.removeOverlay(addressOverlay);
	//先清除上次定位图标
	//var myIcon = new BMap.Icon("../../images/NewEvent.png", new BMap.Size(30, 55));
	var myIcon = new BMap.Icon(iconUrlHead + "images/NewEvent.png", new BMap.Size(30, 55));

	spotOverlay = new BMap.Marker(pt, {
		icon : myIcon
	});
	map.addOverlay(spotOverlay);
	if (spotCircleRadius > 0) {
		spotCircle = new BMap.Circle(pt, spotCircleRadius, {
			strokeColor : "red",
			fillColor : "pink",
			strokeWeight : 2,
			fillOpacity : spotCircleOpacity
		});
		map.addOverlay(spotCircle);
	}
	isSpoted = true;
	//标注成功
}

function markAddressOverlay(pt) {
	map.removeOverlay(addressOverlay);
	//先清除上次定位图标
    //var myIcon = new BMap.Icon("../../images/address-spot.png", new BMap.Size(32, 32));
	var myIcon = new BMap.Icon(iconUrlHead + "images/address-spot.png", new BMap.Size(32, 32));

	addressOverlay = new BMap.Marker(pt, {
		icon : myIcon
	});

	if (isInAccept) {
		var label = new BMap.Label("标注请双击列表", {
			offset : new BMap.Size(-30, 40)
		});
		addressOverlay.setLabel(label);
	} else {
		//解析成gps坐标 先用百度转百度 减去偏移量
		BMap.Convertor.translate(pt, 0, function(point) {
			var gpsx = pt.lng * 2 - point.lng;
			var gpsy = pt.lat * 2 - point.lat;
			//添加信息窗
			var infoWindowTitle = '<div style="font-weight:bold;color:#CE5521;font-size:14px">坐标信息</div>';
			var opts = {
				title : infoWindowTitle,
				width : 200,
				enableMessage : false,
				enableAutoPan : false
			};
			var infoWindowHtml = [];
			infoWindowHtml.push('<table><tbody>');
			infoWindowHtml.push('<tr><td>百度坐标X：' + pt.lng + '</td></tr>');
			infoWindowHtml.push('<tr><td>百度坐标Y：' + pt.lat + '</td></tr>');
			infoWindowHtml.push('<tr><td>GPS坐标X：' + gpsx + '</td></tr>');
			infoWindowHtml.push('<tr><td>GPS坐标Y：' + gpsy + '</td></tr>');
			infoWindowHtml.push('</tbody></table>');
			var infoWindow = new BMap.InfoWindow(infoWindowHtml.join(""), opts);

			addressOverlay.addEventListener("click", function() {
				addressOverlay.openInfoWindow(infoWindow);
			});
		});
	}

	map.addOverlay(addressOverlay);
}

//搜索功能-使用百度的所有结果面板
function localSearch() {
	clearSearch();
	//初始化搜索服务
	localS = new BMap.LocalSearch(map, {
		renderOptions : {
			map : map,
			panel : "r-result",
			autoViewport : false //无需自动调整视野
		}
	});
	//设置每页显示容量
	localS.setPageCapacity(6);
	//设置信息框显示回调。将坐标post给主程序
	localS.setInfoHtmlSetCallback(function(poi, html) {
		//逆地址解析
		var pt = poi.marker.getPosition();
		map.panTo(pt);
		if (isInAccept)//受理中回传
		{
			markSpotOverlay(pt);
			//标注图标
			var gc = new BMap.Geocoder();
			gc.getLocation(pt, function(rs) {
				var addComp = rs.addressComponents;
				var address = poi.title + " " + poi.address;
				//解析成gps坐标 先用百度转百度 减去偏移量
				BMap.Convertor.translate(pt, 0, function(point) {
					var gpsx = pt.lng * 2 - point.lng;
					var gpsy = pt.lat * 2 - point.lat;
					//alert(address + "," + gpsx + "," + gpsy);
					window.external.setMapSpot(address, addComp.district, gpsx, gpsy);

				});
			});
		}
	});

	qc = document.getElementById("querycontent").value;
	localS.search(qc);
}

//本地搜索--仅数据-使用自定义结果面板(easyui datagrid)
function localSearchOnlyData() {
	//var qcontent = document.getElementById("querycontent2").value;
	var qcontent = $("#querycontent2").searchbox("getValue");
	if (qcontent == '')
		return;
	$("#tbQueryResult").datagrid("loadData", []);

	var options = {
		pageCapacity : 50,
		onSearchComplete : function(results) {
			// 判断状态是否正确
			if (local.getStatus() == BMAP_STATUS_SUCCESS) {
				var s = [];
				for (var i = 0; i < results.getCurrentNumPois(); i++) {
					//s.push(results.getPoi(i).title + ", " + results.getPoi(i).address);
					var rr = {};
					rr.title = results.getPoi(i).title;
					rr.address = results.getPoi(i).address;
					rr.lng = results.getPoi(i).point.lng;
					rr.lat = results.getPoi(i).point.lat;
					s.push(rr);
				}

				if (s.length > 0) {
					//以下为本地分页
					$("#tbQueryResult").datagrid("loadData", s.slice(0, 10));
					var pager = $("#tbQueryResult").datagrid("getPager");
					pager.pagination({
						total : s.length,
						onSelectPage : function(pageNo, pageSize) {
							var start = (pageNo - 1) * pageSize;
							var end = start + pageSize;
							$("#tbQueryResult").datagrid("loadData", s.slice(start, end));
							pager.pagination('refresh', {
								total : s.length,
								pageNumber : pageNo
							});
						}
					});
					//本地分页结束

					//默认选择第一行
					$("#tbQueryResult").datagrid("selectRow", 0);
					if (isInAccept)
						dblClickQueryResult(s[0].title, s[0].address, s[0].lng, s[0].lat);
					else
						clickQueryResult(s[0].title, s[0].address, s[0].lng, s[0].lat);
				}

			}
		}
	};
	var local = new BMap.LocalSearch(map, options);
	local.search(qcontent);
}

//单击搜索结果集，显示地点
function clickQueryResult(title, address, lng, lat) {
	var pt = new BMap.Point(lng, lat);
	map.panTo(pt);
	markAddressOverlay(pt);
}

//2016-7-27 zch add   start
function clickVolunGrid(name, telphone, longitude, latitude) {
	var pt = new BMap.Point(longitude, latitude);
	map.panTo(pt);
	//panToVolun(userid);
	// markAddressOverlay(pt);

}

// end

//双击搜索结果集，标注
function dblClickQueryResult(title, address, lng, lat) {
	var pt = new BMap.Point(lng, lat);
	map.panTo(pt);
	if (isInAccept)//受理中回传
	{
		markSpotOverlay(pt);
		//2016-8-9 zch   add  将半径内的志愿者图标显示出来
		//if (EnableVolunteer) {
		//getInPotRList(pt);
		//}
		//标注图标
		var gc = new BMap.Geocoder();
		//逆地址解析
		gc.getLocation(pt, function(rs) {
			var addComp = rs.addressComponents;
			//2015-12-24 涂建刚 修正bug，address和传参冲突，改为 addressForSend
			var addressForSend = title + " " + address;
			//解析成gps坐标 先用百度转百度 减去偏移量
			BMap.Convertor.translate(pt, 0, function(point) {
				var gpsx = pt.lng * 2 - point.lng;
				var gpsy = pt.lat * 2 - point.lat;
				//alert(address + "," + gpsx + "," + gpsy);
				//地图回调窗口函数
				window.external.setMapSpot(addressForSend, addComp.district, gpsx, gpsy);

			});
		});
	}
	//else {
	//	markAddressOverlay(pt);
	//}
}

//清除搜索
function clearSearch() {
	if (localS) {
		localS.clearResults();
	}
}

//清除搜索
function clearSearch2() {
	map.removeOverlay(addressOverlay);
	$("#tbQueryResult").datagrid("loadData", []);
	//$("#querycontent2").textbox("clear");
	$("#querycontent2").searchbox("clear");
}

function getAmbInfoWindowContent(gpsTime, driver, doctor, nurse, litter, taskStateName, showInfo, sendAddr, speed, stationName) {
	var infoWindowHtml = [];
	infoWindowHtml.push('<table><tbody>');
	infoWindowHtml.push('<tr><td>时间：' + gpsTime + '</td></tr>');
    //add2020-09-21 plq 增加归属站点展示
	if (stationName)
	    infoWindowHtml.push('<tr><td>归属站点：' + stationName + '</td></tr>');
	if (driver)
		infoWindowHtml.push('<tr><td>司机：' + driver + '</td></tr>');
	if (doctor)
		infoWindowHtml.push('<tr><td>医生：' + doctor + '</td></tr>');
	if (nurse)
		infoWindowHtml.push('<tr><td>护士：' + nurse + '</td></tr>');
	if (litter)
		infoWindowHtml.push('<tr><td>担架工：' + litter + '</td></tr>');
	infoWindowHtml.push('<tr><td>工作状态：' + taskStateName + '</td></tr>');
	if (showInfo)
		infoWindowHtml.push('<tr><td>任务：' + showInfo + '</td></tr>');
	if (sendAddr)
		infoWindowHtml.push('<tr><td>送往地点：' + sendAddr + '</td></tr>');
	//infoWindowHtml.push('<tr><td>高度：' + height + '米</td></tr>');
	infoWindowHtml.push('<tr><td>速度：' + speed + '公里/小时</td></tr>');
	infoWindowHtml.push('</tbody></table>');

	return infoWindowHtml.join("");
}

//车辆gps--百度坐标系
function alterAmbulanceByBaiduCoor(id, realSign, stationId, stationName, x, y, gpsTime, height, speed, dir, driver, doctor, nurse, litter, taskStateId, taskStateName, showInfo, sendAddr) {
	//alert("" + ambulanceArray.length);
	var findAmb = false;
	for (var i = 0; i < ambulanceArray.length; i++) {
		if (ambulanceArray[i].getTitle() === id) {
			findAmb = true;
			break;
		}
	}
	var myIcon;
	//= new BMap.Icon("images/amb.png", new BMap.Size(32,32));
	var iconPath = "";
	if (taskStateId < 6) {//任务中
		//myIcon = new BMap.Icon("images/amb2.png", new BMap.Size(32,32));
	    //iconPath = "../../images/amb2_" + ambulanceStyle + ".png";
	    iconPath = iconUrlHead + "images/amb2_" + ambulanceStyle + ".png";
	} else if (taskStateId < 8) {//待命中
		//myIcon = new BMap.Icon("images/amb1.png", new BMap.Size(32,32));
	    //iconPath = "../../images/amb1_" + ambulanceStyle + ".png";
	    iconPath = iconUrlHead + "images/amb1_" + ambulanceStyle + ".png";
	} else if (taskStateId == 8) {//不能调用
		//myIcon = new BMap.Icon("images/amb3.png", new BMap.Size(32,32));
	    //iconPath = "../../images/amb3_" + ambulanceStyle + ".png";
	    iconPath = iconUrlHead + "images/amb3_" + ambulanceStyle + ".png";
	} else {//暂停调用
		//myIcon = new BMap.Icon("images/amb4.png", new BMap.Size(32,32));
	    //iconPath = "../../images/amb4_" + ambulanceStyle + ".png";
	    iconPath = iconUrlHead + "images/amb4_" + ambulanceStyle + ".png";
	}
	myIcon = new BMap.Icon(iconPath, new BMap.Size(ambulance_icon_width, ambulance_icon_height));

	if (findAmb) {//不再删除，只是修改车辆信息
		ambulanceArray[i].setIcon(myIcon);
		//先设置图标再设置位置和方向
		ambulanceArray[i].setPosition(new BMap.Point(x, y));
		ambulanceArray[i].setRotation(dir);
		var infoWindowContent = getAmbInfoWindowContent(gpsTime, driver, doctor, nurse, litter, taskStateName, showInfo, sendAddr, speed, stationName);
		ambulanceArray[i].infoWindow.setContent(infoWindowContent);
	} else//没有找到，增加数据
	{
		addAmbToTree(id, realSign, stationId, stationName);

		var marker = new BMap.Marker(new BMap.Point(x, y), {
			icon : myIcon
		});
		map.addOverlay(marker);
		marker.setRotation(dir);
		//设置旋转角度
		var label = new BMap.Label(realSign, {
			offset : new BMap.Size(0, ambulance_icon_height + 5)
		});
		label.setTitle(realSign);
		marker.setLabel(label);
		marker.setTitle(id);

		ambulanceArray.push(marker);

		//添加信息窗
		var infoWindowTitle = '<div style="font-weight:bold;color:#6dd3f2;font-size:14px">' + realSign + '</div>';
		var opts = {
			title : infoWindowTitle,
			width : 200,
			enableMessage : false,
			enableAutoPan : false
		};
		var infoWindowContent = getAmbInfoWindowContent(gpsTime, driver, doctor, nurse, litter, taskStateName, showInfo, sendAddr, speed, stationName);
		var infoWindow = new BMap.InfoWindow(infoWindowContent, opts);

		marker.infoWindow = infoWindow;
		//扩展一个infoWindow 属性
		//marker.rowIndex = rowIndex;//扩展第二个属性 2015-09-01 tjg
		marker.addEventListener("click", function() {
			marker.openInfoWindow(infoWindow);
		});
	}
	if (checkedAmbulanceId != "" && checkedAmbulanceId == id) {
		panToAmb(id);
	}
}

//2016-7-26 zch add volunteer imitate ambulance    start
function getVolunInfoWindowContent(name, sex, birthday, speciality, volunteerType, skill, telphone, gpsTime, workState) {
	var infoWindowHtml = [];
	infoWindowHtml.push('<table  width="98%"  ><tbody>');
	infoWindowHtml.push('<tr><td colspan="2">时间：' + gpsTime.substring(5) + '</td></tr>');
	if (speciality)
		infoWindowHtml.push('<tr><td colspan="2">特长：' + speciality + '</td></tr>');
	if (skill)
		infoWindowHtml.push('<tr><td  colspan="2">技能：' + skill + '</td></tr>');
	if (workState>=0) {
		var workStateName = "";
		switch(workState) {
			case 0:
				workStateName = "未上班";
				break;
			case 1:
				workStateName = "任务中";
				break;
			case 2:
				workStateName = "待命中";
				break;
			default:
				break;
		}
	}
	infoWindowHtml.push('<tr><td colspan="2"> 工作状态：' + workStateName + '</td></tr>');
	infoWindowHtml.push('<tr ><td height="35px";  ><div>点击呼叫： <a class=' + '"' + button_qipao_color + '"' + ' href="javascript:void(0);" onclick="mapCallVolunteer(' + telphone + ');">' + telphone + '</a> </div></td></tr>');
	infoWindowHtml.push('</tbody></table>');
	return infoWindowHtml.join("");
}

//回调到窗口，将拨打电话的号码传过去
function mapCallVolunteer(telphone) {
	window.external.mapCallVolunteer(telphone);
	$.messager.alert('提示','拨号中，请稍后...');    
}

function alterVolunteer(userid, name, sex, birthday, speciality, volunteerType, skill, telphone, workState, longitude, latitude, gpsTime, beginfreeTime, endfreeTime) {
	if (!EnableVolunteer) {
		return;
	}
	var findVolun = false;
	for (var i = 0; i < volunteerArray.length; i++) {
		if (volunteerArray[i].getTitle() == userid) {
			findVolun = true;
			break;
		}
	}
	if (findVolun) {//不再删除，只是修改信息
		if (workState == 1000) {//当workState为1000 时，相当于null, 不改变状态
			workState = volunteerArray[i].workState;
		}
		var myIcon;
		var iconPath = "";
		if (workState == 1) {//任务中 男
		    //iconPath = "../../images/volun1.png";
		    iconPath = iconUrlHead + "images/volun1.png";
		} else if (workState == 2) {//待命中
		    //iconPath = "../../images/volun2.png";
		    iconPath = iconUrlHead + "images/volun2.png";
		} else {//不能调用
		    //iconPath = "../../images/volun0.png";
		    iconPath = iconUrlHead + "images/volun0.png";
		}
		myIcon = new BMap.Icon(iconPath, new BMap.Size(volunteer_icon_width, volunteer_icon_height));
		volunteerArray[i].setIcon(myIcon);
		volunteerArray[i].setPosition(new BMap.Point(longitude, latitude));
		var infoWindowContent = getVolunInfoWindowContent(name, sex, birthday, speciality, volunteerType, skill, telphone, gpsTime, workState);
		volunteerArray[i].infoWindow.setContent(infoWindowContent);
		//更新volunteerArray 属性
		volunteerArray[i].workState = workState;
		volunteerArray[i].name = name;
		volunteerArray[i].sex = sex;
		volunteerArray[i].birthday = birthday;
		volunteerArray[i].speciality = speciality;
		volunteerArray[i].volunteerType = volunteerType;
		volunteerArray[i].skill = skill;
		volunteerArray[i].telphone = telphone;
		volunteerArray[i].longitude = longitude;
		volunteerArray[i].latitude = latitude;
		volunteerArray[i].gpsTime = gpsTime;
		volunteerArray[i].beginfreeTime = beginfreeTime;
		volunteerArray[i].endfreeTime = endfreeTime;
	} else//没有找到，增加数据
	{
		if (workState == 1000) {
			workState = 2;
		}//首次添加，如果没有状态就默认为待命
		var iconPath = "";
		if (workState == 1) {//任务中 男
		    //iconPath = "../../images/volun1.png";
		    iconPath = iconUrlHead + "images/volun1.png";
		} else if (workState == 2) {//待命中
		    //iconPath = "../../images/volun2.png";
		    iconPath = iconUrlHead + "images/volun2.png";
		} else if (workState == 0) {//不能调用
		    //iconPath = "../../images/volun0.png";
		    iconPath = iconUrlHead + "images/volun0.png";
		}
		myIcon = new BMap.Icon(iconPath, new BMap.Size(volunteer_icon_width, volunteer_icon_height));
		var marker = new BMap.Marker(new BMap.Point(longitude, latitude), {
			icon : myIcon
		});
		map.addOverlay(marker);
		var label = new BMap.Label(name, {
			offset : new BMap.Size(0, volunteer_icon_height + 3)
		});
		label.setTitle(name);
		marker.setLabel(label);
		marker.setTitle(userid);
		//添加信息窗
		var infoWindowTitle = '<div ><span style="font-weight:bold;color:#CE5521;font-size:15px">' + volunteerType + ": " + name + "&nbsp;&nbsp;&nbsp;" + sex + "&nbsp;&nbsp;&nbsp;" + birthday + '</span> </div>';
		var opts = {
			title : infoWindowTitle,
			width : 250,
			enableMessage : false,
			enableAutoPan : false
		};
		var infoWindowContent = getVolunInfoWindowContent(name, sex, birthday, speciality, volunteerType, skill, telphone, gpsTime, workState);
		var infoWindow = new BMap.InfoWindow(infoWindowContent, opts);
		marker.infoWindow = infoWindow;
		marker.addEventListener("click", function() {
			marker.openInfoWindow(infoWindow);
		});
		marker.userid = userid;
		marker.name = name;
		marker.sex = sex;
		marker.birthday = birthday;
		marker.speciality = speciality;
		marker.volunteerType = volunteerType;
		marker.skill = skill;
		marker.telphone = telphone;
		marker.workState = workState;
		marker.longitude = longitude;
		marker.latitude = latitude;
		marker.gpsTime = gpsTime;
		marker.beginfreeTime = beginfreeTime;
		marker.endfreeTime = endfreeTime;
		volunteerArray.push(marker);
		//addVolunToGrid(userid, name, volunteerType, telphone, longitude, latitude);
	}
}

//移动到志愿者位置 并且打开气泡  zch
function panToVolun(userid) {

	for (var i = 0; i < volunteerArray.length; i++) {
		if (volunteerArray[i].userid == userid) {
			map.centerAndZoom(volunteerArray[i].getPosition(), map.getZoom());
			volunteerArray[i].openInfoWindow(volunteerArray[i].infoWindow);
			break;
		}
	}
}

//删除志愿者  zch
function deleteVolun(userid) {
	var findVolun = false;
	for (var i = 0; i < volunteerArray.length; i++) {
		if (volunteerArray[i].getTitle() == userid) {
			findVolun = true;
			break;
		}
	}
	if (findVolun) {
		map.removeOverlay(volunteerArray[i]);
		//删除地图图标
		volunteerArray.splice(i, 1);
		//删除数组元素
		deleteVolunFromGrid(userid);
	}
}

//半径改变   2016-8-3  zch
function VolunChangeR(r) {
	changeSpotCircleRadius(r);
}

//收到志愿者app的状态改变    zch
function ChangeAPPVolunState(UserId, workState) {
	if (workState != 1000) {//状态为1000时，相当于null
		for (var k = 0; k < volunteerArray.length; k++) {//将定位坐标与所有志愿者位置坐标比较
			if (volunteerArray[k].userid == UserId) {
				volunteerArray[k].workState = workState;
				alterVolunteer(volunteerArray[k].userid, volunteerArray[k].name, volunteerArray[k].sex, volunteerArray[k].birthday, volunteerArray[k].speciality, volunteerArray[k].volunteerType, volunteerArray[k].skill, volunteerArray[k].telphone, volunteerArray[k].workState, volunteerArray[k].longitude, volunteerArray[k].latitude, volunteerArray[k].gpsTime, volunteerArray[k].beginfreeTime, volunteerArray[k].endfreeTime);
				break;
			}
		}
	}
}

// end

//车辆gps---gps坐标系
function alterAmbulanceByGpsCoor(id, realSign, stationId, stationName, x, y, gpsTime, height, speed, dir, driver, doctor, nurse, taskStateId, taskStateName, showInfo) {
	var gpsPoint = new BMap.Point(x, y);
	BMap.Convertor.translate(gpsPoint, 0, function(point) {
		alterAmbulanceByBaiduCoor(id, realSign, stationId, stationName, point.lng, point.lat, gpsTime, height, speed, dir, driver, doctor, nurse, taskStateId, taskStateName, showInfo);
	});
}

//移动到车辆位置 并且打开气泡
function panToAmb(ambId) {
	//alert(ambId);
	for (var i = 0; i < ambulanceArray.length; i++) {
		if (ambulanceArray[i].getTitle() === ambId) {
			//map.panTo(ambulanceArray[i].getPosition());
			map.centerAndZoom(ambulanceArray[i].getPosition(), map.getZoom());
			//2015-11-27 不调整缩放等级
			ambulanceArray[i].openInfoWindow(ambulanceArray[i].infoWindow);
			break;
		}
	}
}

//删除车辆
function deleteAmb(ambId, stationId) {
	var findAmb = false;
	for (var i = 0; i < ambulanceArray.length; i++) {
		if (ambulanceArray[i].getTitle() === ambId) {
			findAmb = true;
			break;
		}
	}
	if (findAmb) {
		deleteAmbFromTree(ambId, stationId);
		map.removeOverlay(ambulanceArray[i]);
		//删除地图图标
		ambulanceArray.splice(i, 1);
		//删除数组元素
	}
}

//车辆到现场地址的路径规划
function ambToSpotRoute(ambId) {
	clearAmbRoute();
	if (isSpoted) {
		for (var i = 0; i < ambulanceArray.length; i++) {
			if (ambulanceArray[i].getTitle() === ambId) {
				//alert(ambId);
				//ambulanceArray[i].getPosition()
				var tmpAmbRealSign = ambulanceArray[i].getLabel().getTitle();
				var options = {
					onSearchComplete : function(results) {
						//alert(ambDriving.getStatus());
						if (ambDriving.getStatus() == BMAP_STATUS_SUCCESS) {
							// 获取第一条方案
							var plan = results.getPlan(0);
							var distance = plan.getDistance();
							var duration = plan.getDuration();
							//alert(distance + "," + duration);

							Gid('routeResult').style.display = "";
							Gid("routeResult").innerHTML = tmpAmbRealSign + "到现场最短时间为：" + duration + "，距离为:" + distance;
						}
					},
					renderOptions : {
						map : map,
						autoViewport : true
					}
				};
				ambDriving = new BMap.DrivingRoute(map, options);
				ambDriving.search(ambulanceArray[i].getPosition(), spotOverlay.getPosition());
				break;
			}
		}
	}
}

//自主导航
function selfRoute(routePolicyIndex) {
	clearAmbRoute();
	var rp = routePolicy[routePolicyIndex];
	//默认最少时间
	if (routeBegin && routeEnd) {

		var options = {
			onSearchComplete : function(results) {
				//alert(ambDriving.getStatus());
				if (ambDriving.getStatus() == BMAP_STATUS_SUCCESS) {
					// 获取第一条方案
					var plan = results.getPlan(0);
					var distance = plan.getDistance();
					var duration = plan.getDuration();
					//alert(distance + "," + duration);
					var tab = $('#selfRouteTab').tabs('getSelected');
					// 获取选择的面板
					$('#selfRouteTab').show();
					$('#selfRouteTab').tabs('update', {
						tab : tab,
						options : {
							content : "导航最短时间为：" + duration + "，距离为:" + distance
						}
					});
				}
			},
			renderOptions : {
				map : map,
				autoViewport : true
			},
			policy : rp
		};
		ambDriving = new BMap.DrivingRoute(map, options);
		ambDriving.search(routeBegin.getPosition(), routeEnd.getPosition());

	}
}

function clearAmbRoute() {
	Gid('routeResult').style.display = "none";
	if (ambDriving)
		ambDriving.clearResults();
}

//车辆轨迹 依据百度坐标系
function addAmbGpsTrackByBaiduCoor(id, realSign, workState, time, x, y, height, speed, dir) {
    //var myIcon = new BMap.Icon("../../images/gpstrack.png", new BMap.Size(32, 32));
    var myIcon = new BMap.Icon(iconUrlHead + "images/gpstrack.png", new BMap.Size(32, 32));

	var marker = new BMap.Marker(new BMap.Point(x, y), {
		icon : myIcon
	});

	map.addOverlay(marker);
	marker.setRotation(dir);
	//设置旋转角度
	var label = new BMap.Label(realSign, {
		offset : new BMap.Size(20, 40)
	});
	marker.setLabel(label);
	marker.setTitle(id);

	ambGpsTrackArray.push(marker);

	//添加信息窗
	var infoWindowTitle = '<div style="font-weight:bold;color:#CE5521;font-size:14px">' + realSign + '</div>';
	var opts = {
		title : infoWindowTitle,
		width : 200,
		enableMessage : false,
		enableAutoPan : false
	};
	var infoWindowHtml = [];
	infoWindowHtml.push('<table><tbody>');
	infoWindowHtml.push('<tr><td>时间:' + time + '</td></tr>');
	infoWindowHtml.push('<tr><td>工作状态:' + workState + '</td></tr>');
	infoWindowHtml.push('<tr><td>经度:' + x + '</td></tr>');
	infoWindowHtml.push('<tr><td>纬度:' + y + '</td></tr>');
	infoWindowHtml.push('<tr><td>高度:' + height + '</td></tr>');
	infoWindowHtml.push('<tr><td>速度:' + speed + '</td></tr>');
	infoWindowHtml.push('<tr><td>方向:' + dir + '</td></tr>');
	infoWindowHtml.push('</tbody></table>');
	var infoWindow = new BMap.InfoWindow(infoWindowHtml.join(""), opts);
	marker.infoWindow = infoWindow;

	marker.addEventListener("click", function() {
		marker.openInfoWindow(infoWindow);
	});
}

//添加多点轨迹回放 drawstyle: 画图样式 0表示推荐，1表示所有点+线,2表示所有点,3表示路书
function addMultiAmbGpsTrack(jsonstr, drawstyle) {
	//alert(jsonstr);
	//将字符串转为json数组，目前树形：RealSign,Dir,Time,X,Y
	//jsonstr = '[{"Code":"00101","RealSign":"A-T2072","WorkStateId":5,"WorkState":"医院交接","GpsTime":"2015-06-27 17:00:00","Longitude":116.5694409102603,"Latitude":39.553637245978713,"Height":365,"Speed":97,"Direction":76}]';
	if (!drawstyle)
		drawstyle = 0;
	//推荐

	var gpsTrackList = eval('(' + jsonstr + ')');
	//JSON.parse(jsonstr);
	var pointArray = [];
	//轨迹点数组，用于调整地图视野
	var trackcount = gpsTrackList.length;

	for ( i = 0; i < trackcount; i++) {
		var isdrawpoint = false;
		if (drawstyle < 3) {
			if (drawstyle == 0) {
				if ((i == 0) || (i == trackcount - 1))
					isdrawpoint = true;
				else
					isdrawpoint = false;
			} else
				isdrawpoint = true;
			if (isdrawpoint) {
				addAmbGpsTrackByBaiduCoor(gpsTrackList[i].Code + gpsTrackList[i].GpsTime, gpsTrackList[i].RealSign, gpsTrackList[i].WorkState, gpsTrackList[i].GpsTime, gpsTrackList[i].Longitude, gpsTrackList[i].Latitude, gpsTrackList[i].Height, gpsTrackList[i].Speed, gpsTrackList[i].Direction);
			}
		}

		pointArray.push(new BMap.Point(gpsTrackList[i].Longitude, gpsTrackList[i].Latitude));
	}

	if ((drawstyle == 0) || (drawstyle == 1)) {
		ambGpsTrackLine = new BMap.Polyline(pointArray, {
			strokeColor : "blue",
			strokeWeight : 6,
			strokeStyle : "solid"
		});
		map.addOverlay(ambGpsTrackLine);
		//画线
		map.setViewport(pointArray);

	} else if (drawstyle == 3) {//路书功能

		ambGpsTrackLine = new BMap.Polyline(pointArray, {
			strokeColor : "blue",
			strokeWeight : 6,
			strokeStyle : "solid"
		});
		map.addOverlay(ambGpsTrackLine);
		//画线
		map.setViewport(pointArray);

		if (lushu)
			lushu.clear();

		lushu = new BMapLib.LuShu(map, pointArray, {
		    //icon: new BMap.Icon("../../images/gpstrack_r.png", new BMap.Size(50, 50)),
		    icon: new BMap.Icon(iconUrlHead + "images/gpstrack_r.png", new BMap.Size(50, 50)),
			speed : 4500,
			enableRotation : true,
			autoView : false, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
			landmarkPois : []
		});
		lushu.start();
	}

	//alert(gpsTrackList.length + ' ' + gpsTrackList[0].Time);
}

//清除轨迹回放
function clearAmbGpsTrack() {
	for ( i = 0; i < ambGpsTrackArray.length; i++) {
		map.removeOverlay(ambGpsTrackArray[i]);
		//删除地图图标
	}

	ambGpsTrackArray.length = 0;

	if (ambGpsTrackLine) {
	    map.removeOverlay(ambGpsTrackLine);
	}

	if (lushu) {
		lushu.clear();
		lushu = null;
	}
}

//移动到轨迹处
function panToGpsTrack(ambCode, gpsTime) {
	var trackId = ambCode + gpsTime;
	for (var i = 0; i < ambGpsTrackArray.length; i++) {
		if (ambGpsTrackArray[i].getTitle() === trackId) {
			map.panTo(ambGpsTrackArray[i].getPosition());
			ambGpsTrackArray[i].openInfoWindow(ambGpsTrackArray[i].infoWindow);
			break;
		}
	}
}

//清除定位点及圆圈
function clearSpotMark() {
	map.removeOverlay(spotOverlay);
	//删除定位地点
	map.removeOverlay(spotCircle);
}

//清除所有呼救事件
function clearAlarmEventMark() {
	for ( i = 0; i < alarmEventArray.length; i++) {
		map.removeOverlay(alarmEventArray[i]);
		//删除地图图标
	}

	alarmEventArray.length = 0;
}

//清除所有车辆
function clearAllAmbulance() {
	for ( i = 0; i < ambulanceArray.length; i++) {
		map.removeOverlay(ambulanceArray[i]);
		//删除地图图标
	}

	ambulanceArray.length = 0;
}

//清除所有分站
function clearAllStation() {
	for ( i = 0; i < stationArray.length; i++) {
		map.removeOverlay(stationArray[i]);
		//删除地图图标
	}

	stationArray.length = 0;
}

//清除所有医院
function clearAllHospital() {
	for ( i = 0; i < hospitalArray.length; i++) {
		map.removeOverlay(hospitalArray[i]);
		//删除地图图标
	}

	hospitalArray.length = 0;
}

//增加呼救事件标注
function addAlarmEventByBaiduCoor(id, x, y, taskInfo, linkName, linkCall, typeId) {
	deleteAlarmEvent(id);
	//先删除一下

	//alert("begin marker");
	var myIcon;
	if (typeId == 1) {//任务中
	    //myIcon = new BMap.Icon("../../images/tasking.png", new BMap.Size(28, 41));
	    myIcon = new BMap.Icon(iconUrlHead + "images/tasking.png", new BMap.Size(28, 41));
	} else if (typeId == 2) {//挂起
	    //myIcon = new BMap.Icon("../../images/hangup.png", new BMap.Size(28, 41));
	    myIcon = new BMap.Icon(iconUrlHead + "images/hangup.png", new BMap.Size(28, 41));
	} else if (typeId == 3) {//预约
	    //myIcon = new BMap.Icon("../../images/appoint.png", new BMap.Size(28, 41));
	    myIcon = new BMap.Icon(iconUrlHead + "images/appoint.png", new BMap.Size(28, 41));
	} else {//已经结束
	    //myIcon = new BMap.Icon("../../images/end.png", new BMap.Size(28, 41));
	    myIcon = new BMap.Icon(iconUrlHead + "images/end.png", new BMap.Size(28, 41));
		//alert("end.png");
	}

	var marker = new BMap.Marker(new BMap.Point(x, y), {
		icon : myIcon
	});

	map.addOverlay(marker);
	marker.setTitle(id);

	alarmEventArray.push(marker);

	//添加信息窗
	var infoWindowTitle = '<div style="font-weight:bold;color:#CE5521;font-size:14px">任务信息</div>';
	var opts = {
		title : infoWindowTitle,
		width : 200,
		enableMessage : false,
		enableAutoPan : false
	};
	var infoWindowHtml = [];
	infoWindowHtml.push('<table><tbody>');
	if (linkName) {
		infoWindowHtml.push('<tr><td>联系人：' + linkName + '</td></tr>');
	}
	if (linkCall) {
		infoWindowHtml.push('<tr><td>联系电话：' + linkCall + '</td></tr>');
	}
	infoWindowHtml.push('<tr><td>事件名称：' + taskInfo + '</td></tr>');
	infoWindowHtml.push('</tbody></table>');
	var infoWindow = new BMap.InfoWindow(infoWindowHtml.join(""), opts);
	marker.infoWindow = infoWindow; //add2020-11-04 plq

	marker.addEventListener("click", function() {
		marker.openInfoWindow(infoWindow);
	});
}

//删除单个事件
function deleteAlarmEvent(eventId) {
	var findEvent = false;
	for (var i = 0; i < alarmEventArray.length; i++) {
		if (alarmEventArray[i].getTitle() === eventId) {
			findEvent = true;
			break;
		}
	}

	if (findEvent) {
		map.removeOverlay(alarmEventArray[i]);
		//删除地图图标
		alarmEventArray.splice(i, 1);
		//删除数组元素
	}
}

//修改呼救电话位置
function alterTelMarkerByBaiduCoor(x, y, telCode) {
	map.removeOverlay(telOverlay);
	//先清除上次电话图标
	alert(telCode);
    //var myIcon = new BMap.Icon("../../images/TelTag.png", new BMap.Size(tel_icon_width, tel_icon_height));
	var myIcon = new BMap.Icon(iconUrlHead + "images/TelTag.png", new BMap.Size(tel_icon_width, tel_icon_height));

	telOverlay = new BMap.Marker(new BMap.Point(x, y), {
		icon : myIcon
	});
	//2016-8-19 zch 添加title
	var label = new BMap.Label(telCode, {
		offset : new BMap.Size(0, ambulance_icon_height + 5)
	});
	label.setTitle("呼救地址");
	telOverlay.setLabel(label);
	//end
	map.addOverlay(telOverlay);
	panTo(x, y);
}

//增加分站标记
function addStationByBaiduCoor(id, name, x, y) {
    //var myIcon = new BMap.Icon("../../images/station.png", new BMap.Size(40, 40));
    var myIcon = new BMap.Icon(iconUrlHead + "images/station.png", new BMap.Size(40, 40));

	var marker = new BMap.Marker(new BMap.Point(x, y), {
		icon : myIcon
	});

	map.addOverlay(marker);
	var label = new BMap.Label(name, {
		offset : new BMap.Size(0, 40)
	});
	marker.setLabel(label);
	marker.setTitle(id);

	stationArray.push(marker);
}

//增加医院标记
function addHospitalByBaiduCoor(id, name, x, y) {
    //var myIcon = new BMap.Icon("../../images/hospital.png", new BMap.Size(48, 48));
    var myIcon = new BMap.Icon(iconUrlHead + "images/hospital.png", new BMap.Size(40, 40));

	var marker = new BMap.Marker(new BMap.Point(x, y), {
		icon : myIcon
	});

	map.addOverlay(marker);
	var label = new BMap.Label(name, {
	    //offset: new BMap.Size(0, 45)
	    offset: new BMap.Size(0, 40)
	});
	marker.setLabel(label);
	marker.setTitle(id);

	hospitalArray.push(marker);
}

//地图移动
function panTo(x, y) {
	map.panTo(new BMap.Point(x, y));
}

//移动and缩放
function zoomTo(x, y, zoom) {
	map.centerAndZoom(new BMap.Point(x, y), zoom);
}

//地图单击事件
function mapClickEvent(e) {
	var pt = e.point;

	//解析成gps坐标 先用百度转百度 减去偏移量
	BMap.Convertor.translate(pt, 0, function(point) {
		var gpsx = pt.lng * 2 - point.lng;
		var gpsy = pt.lat * 2 - point.lat;

		if (isInAccept)//受理中
		{
			markSpotOverlay(pt);
			//2016-8-9 zch   add  将半径内的志愿者图标显示出来
			//if (EnableVolunteer) {
			//getInPotRList(pt);
			//}
			//标注图标
			//逆地址解析
			var gc = new BMap.Geocoder();
			gc.getLocation(pt, function(rs) {
				var addComp = rs.addressComponents;
				var address = addComp.district + addComp.street + addComp.streetNumber;
				//区县+街道+门牌号
				//地图回调窗口函数
				window.external.setMapSpot(address, addComp.district, gpsx, gpsy);

				//alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
			});

		} else {
			var showedmsg = "百度坐标X:" + pt.lng + ",百度坐标Y:" + pt.lat + "<br/>GPS坐标X:" + gpsx + ",GPS坐标Y:" + gpsy;
			$.messager.show({
				title : "单击点的坐标信息",
				msg : showedmsg,
				timeout : 20000,
				showType : "fade",
				width : "400px",
				height : "200px",
				style : {
					right : '',
					top : $(document).scrollTop() + ($(window).height() - 250) * 0.5, //document.body.scrollTop+document.documentElement.scrollTop,
					bottom : ''
				}
			});
			$.parser.parse(); //add2020-09-15 plq 不带参数，默认解析该页面中全部被定义为easyui组件的节点。

			//alert("百度坐标X:" + pt.lng + ",百度坐标Y:" + pt.lat + "\r\nGPS坐标X:" + gpsx + ",GPS坐标Y:" + gpsy);
		}
	});

	removeMapClickEvent(); 

	//移除单击事件
	map.setDefaultCursor(panCursor);
	//恢复默认样式
	btnInit(1); //内部代码也执行了一次removeMapClickEvent
	//初始化按钮，选择pan
}

//添加地图单击事件 
function addMapClickEvent() {
    //console.log(isMapAddClickEvent);
    //防止多次添加
	if (!isMapAddClickEvent) { //地图未绑定单击事件
	    map.addEventListener("click", mapClickEvent);
		isMapAddClickEvent = true;
	}
}

//移除地图单击事件 
function removeMapClickEvent() {
	if (isMapAddClickEvent) {//防止多次移除
	    map.removeEventListener("click", mapClickEvent); //第二次添加然后移除地图单击事件时并没有成功注销掉，官网demo也是这样
		//移除单击事件
		isMapAddClickEvent = false;
	}
}

//设置定位圆圈半径，单位：米
function setSpotCircleRadius(radius) {
	spotCircleRadius = radius;
}

//修改定位圆圈半径,单位 米
function changeSpotCircleRadius(radius) {
	if (isSpoted && spotCircleRadius > 0) {
		if (spotCircle) {
			spotCircle.setRadius(radius);
		}
	}
}

//根据坐标直接进入标注态
function enterSpotStateByBaiduCoor(x, y) {
	acceptStart(true);
	var pt = new BMap.Point(x, y);
	map.panTo(pt);
	markSpotOverlay(pt);
	//标注图标
}


//add2020-09-21 plq 清空车辆树节点
function clearAmbTree() {
    $("#ambTree").tree('loadData', []);
    //var roots = $("#ambTree").tree("getRoots");
    //console.log(roots);
    //console.log(roots.length);
    //if (roots && roots.length > 0) {
    //    for (var i = 0; i < roots.length; i++) {
    //        console.log(roots[i]);
    //        var stationNode = roots[i];
    //        $("#ambTree").tree("remove", stationNode.target); //因为遍历时移除，导致roots.length变化---不能全部移除
    //    }
    //}
    //console.log(roots);
}


//add2020-10-10 plq 防病车 start
//车辆gps--百度坐标系
function alterFbAmbByBaiduCoor(id, realSign, stationId, stationName, x, y, gpsTime, height, speed, dir, driver, doctor, nurse, litter, taskStateId, taskStateName, showInfo, sendAddr, HuJiuLeiXing, iconUrlHead) {
    //alert("" + ambulanceArray.length);
    var findAmb = false;
    for (var i = 0; i < fbAmbArray.length; i++) {
        if (fbAmbArray[i].getTitle() === id) {
            findAmb = true;
            break;
        }
    }
    var myIcon;
    //= new BMap.Icon("images/amb.png", new BMap.Size(32,32));
    var iconPath = "";
    if (taskStateId < 6) {//任务中
        //myIcon = new BMap.Icon("images/amb2.png", new BMap.Size(32,32));
        //iconPath = "../../images/amb2_" + newAmbulanceStyle + ".png";
        iconPath = iconUrlHead + "images/amb2_" + newAmbulanceStyle + ".png"; //add2020-10-23 plq
    } else if (taskStateId < 8) {//待命中
        //myIcon = new BMap.Icon("images/amb1.png", new BMap.Size(32,32));
        //iconPath = "../../images/amb4_" + newAmbulanceStyle + ".png";
        iconPath = iconUrlHead + "images/amb4_" + newAmbulanceStyle + ".png";
    } else if (taskStateId == 8) {//不能调用
        //myIcon = new BMap.Icon("images/amb3.png", new BMap.Size(32,32));
        //iconPath = "../../images/amb3_" + newAmbulanceStyle + ".png";
        iconPath = iconUrlHead + "images/amb3_" + newAmbulanceStyle + ".png";
    } else {//暂停调用
        //myIcon = new BMap.Icon("images/amb4.png", new BMap.Size(32,32));
        //iconPath = "../../images/amb1_" + newAmbulanceStyle + ".png";
        iconPath = iconUrlHead + "images/amb1_" + newAmbulanceStyle + ".png";
    }
    myIcon = new BMap.Icon(iconPath, new BMap.Size(ambulance_icon_width, ambulance_icon_height));

    if (findAmb) {//不再删除，只是修改车辆信息
        fbAmbArray[i].setIcon(myIcon);
        //先设置图标再设置位置和方向
        fbAmbArray[i].setPosition(new BMap.Point(x, y));
        fbAmbArray[i].setRotation(dir);
        var infoWindowContent = getAmbInfoWindowContentNew(gpsTime, driver, doctor, nurse, litter, taskStateName, showInfo, sendAddr, speed, stationName, HuJiuLeiXing);
        fbAmbArray[i].infoWindow.setContent(infoWindowContent);
        //更新Array 属性
        fbAmbArray[i].Station = stationName;
        fbAmbArray[i].RealSign = realSign;
        fbAmbArray[i].WorkState = taskStateName;
        fbAmbArray[i].HuJiuLeiXing = HuJiuLeiXing;
    } else//没有找到，增加数据
    {
        var marker = new BMap.Marker(new BMap.Point(x, y), {
            icon: myIcon
        });
        map.addOverlay(marker);
        marker.setRotation(dir);
        //设置旋转角度
        var label = new BMap.Label(realSign, {
            offset: new BMap.Size(0, ambulance_icon_height + 5)
        });
        label.setTitle(realSign);
        marker.setLabel(label);
        marker.setTitle(id);

        //添加信息窗
        var infoWindowTitle = '<div style="font-weight:bold;color:#6dd3f2;font-size:14px">' + realSign + '</div>';
        var opts = {
            title: infoWindowTitle,
            width: 200,
            enableMessage: false,
            enableAutoPan: false
        };
        var infoWindowContent = getAmbInfoWindowContentNew(gpsTime, driver, doctor, nurse, litter, taskStateName, showInfo, sendAddr, speed, stationName, HuJiuLeiXing);
        var infoWindow = new BMap.InfoWindow(infoWindowContent, opts);

        marker.infoWindow = infoWindow;
        //扩展一个infoWindow 属性
        //marker.rowIndex = rowIndex;//扩展第二个属性 2015-09-01 tjg
        marker.addEventListener("click", function () {
            marker.openInfoWindow(infoWindow);
        });

        marker.Code = id;
        marker.Station = stationName;
        marker.RealSign = realSign;
        marker.WorkState = taskStateName;
        marker.HuJiuLeiXing = HuJiuLeiXing;
        fbAmbArray.push(marker);
    }
}

function getAmbInfoWindowContentNew(gpsTime, driver, doctor, nurse, litter, taskStateName, showInfo, sendAddr, speed, stationName, HuJiuLeiXing) {
    var infoWindowHtml = [];
    infoWindowHtml.push('<table><tbody>');
    infoWindowHtml.push('<tr><td>时间：' + gpsTime + '</td></tr>');
    //add2020-09-21 plq 增加归属站点展示
    if (stationName)
        infoWindowHtml.push('<tr><td>归属站点：' + stationName + '</td></tr>');
    if (driver)
        infoWindowHtml.push('<tr><td>司机：' + driver + '</td></tr>');
    if (doctor)
        infoWindowHtml.push('<tr><td>医生：' + doctor + '</td></tr>');
    if (nurse)
        infoWindowHtml.push('<tr><td>护士：' + nurse + '</td></tr>');
    if (litter)
        infoWindowHtml.push('<tr><td>担架工：' + litter + '</td></tr>');
    infoWindowHtml.push('<tr><td>工作状态：' + taskStateName + '</td></tr>');
    //add2020-10-10 plq 呼救类型(事件类型)
    if (HuJiuLeiXing)
        infoWindowHtml.push('<tr><td>呼救类型：' + HuJiuLeiXing + '</td></tr>');
    if (showInfo)
        infoWindowHtml.push('<tr><td>任务：' + showInfo + '</td></tr>');
    if (sendAddr)
        infoWindowHtml.push('<tr><td>送往地点：' + sendAddr + '</td></tr>');
    //infoWindowHtml.push('<tr><td>高度：' + height + '米</td></tr>');
    infoWindowHtml.push('<tr><td>速度：' + speed + '公里/小时</td></tr>');
    infoWindowHtml.push('</tbody></table>');

    return infoWindowHtml.join("");
}

//移动到车辆位置 并且打开气泡
function panToAmbNew(ambId) {
    //alert(ambId);
    for (var i = 0; i < fbAmbArray.length; i++) {
        if (fbAmbArray[i].getTitle() === ambId) {
            //map.panTo(ambulanceArray[i].getPosition());
            map.centerAndZoom(fbAmbArray[i].getPosition(), map.getZoom());
            //2015-11-27 不调整缩放等级
            fbAmbArray[i].openInfoWindow(fbAmbArray[i].infoWindow);
            break;
        }
    }
}

//清除所有防病车辆定位点
function clearAllFbAmb() {
    for (i = 0; i < fbAmbArray.length; i++) {
        map.removeOverlay(fbAmbArray[i]);
        //删除地图图标
    }

    fbAmbArray.length = 0; //js将length赋值为0清空数组
}
//防病车 end


//移动到呼救事件标注点并打开信息框 add2020-11-04 plq
function panToAlarmLocation(EventCode) {
    for (var i = 0; i < alarmEventArray.length; i++) {
        if (alarmEventArray[i].getTitle() === EventCode) {
            map.panTo(alarmEventArray[i].getPosition());
            alarmEventArray[i].openInfoWindow(alarmEventArray[i].infoWindow);
            break;
        }
    }
}


//隐藏所有车辆 add2020-11-09 plq
function hideAllAmb(ishide) {
    for (var i = 0; i < ambulanceArray.length; i++) {
        if (ishide) {
            ambulanceArray[i].hide();
            //2019/7/18 hxzh 已打开监控窗口则关闭
            //if (ambulanceArray[i].infoBox && ambulanceArray[i].infoBox._isOpen)
            //    ambulanceArray[i].infoBox.close();
        } else {
            ambulanceArray[i].show();
        }
    }
}

//add2021-01-16 plq 清空地图上所有标注点
function clearAllOverlay() {
    var allOverlay = map.getOverlays();//获取所有覆盖物
    for (var i = 0; i < allOverlay.length; i++) {
        map.removeOverlay(allOverlay[i]);
    }
}
